
package com.example.wifi_scan;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.strictmode.Violation;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 主Activity，实现采集、发送、扫描功能
 */

@SuppressWarnings("unused")
public class MainActivity extends Activity {

    private int i = 1;
    boolean flag = true;
    private RSSI rssi = null;

    private List<String> wifiList = new ArrayList<>();
    private WifiManager wifiManager;

    private TextView wifiText, showSelectedWiFi;
    private Button gather, scan, location, stopLocation; //四个按钮
    private EditText number;
    private StringBuffer buffer, tempbuffer;

    private static final int COMPLETED = 0;

    public static final int START = 1;
    public static final int END = 2;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case SendDateToServer.SEND_SUCCESS:
                    break;
                case SendDateToServer.SEND_FAIL:
                    Toast.makeText(MainActivity.this, "发送失败,请查看是否已经填写编号，或是否打开网络连接", Toast.LENGTH_SHORT).show();
                    break;
                case COMPLETED:
                    wifiText.setText(tempbuffer);
                    break;
                case START:
                    number.setEnabled(false);
                    location.setEnabled(false);
                    gather.setEnabled(false);
                    scan.setEnabled(false);
                    stopLocation.setEnabled(true);
                    break;
                case END:
                    number.setEnabled(true);
                    location.setEnabled(true);
                    gather.setEnabled(true);
                    scan.setEnabled(true);
                    stopLocation.setEnabled(false);
                    break;
                default:
                    break;
            }

        }

    };

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showSelectedWiFi = (TextView) findViewById(R.id.showSelectedWiFI);
        wifiText = (TextView) findViewById(R.id.wifi);
        number = (EditText) findViewById(R.id.number);
        number.setText("114514");
        gather = (Button) findViewById(R.id.button);
        scan = (Button) findViewById(R.id.scan);
        location = (Button) findViewById(R.id.location);
        stopLocation = (Button) findViewById(R.id.stopLocation);

        buffer = new StringBuffer();
        //首先将采集和定位按钮设为不可点击，等点击扫描按钮选择了AP后再设为可点击
        location.setEnabled(false);
        gather.setEnabled(false);
        stopLocation.setEnabled(false);

        wifiText.setMovementMethod(ScrollingMovementMethod.getInstance());
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);


        //采集
        gather.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.sendEmptyMessage(START);

                i = 0;
                rssi.setNumber(Integer.parseInt(number.getText().toString()));

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub

                        for (int i2 = 0; i2 < 2; i2++) {
                            scanWifiResult();
                            try {
                                Thread.sleep(3000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        //获取10次扫描数据
                        for (int i1 = 0; i1 < 10; i1++) {
                            //扫描列表，获取wifi列表

                            List<ScanResult> results = scanWifiResult();
                            tempbuffer = new StringBuffer();
                            //对扫描结果进行处理
                            if (results.isEmpty())
                                tempbuffer.append("!获取wifi列表失败\n");
                            else {
                                tempbuffer.append("\n获取wifi列表成功：\n");
                                for (ScanResult result : results) {

                                    //进行判断，将获取到的rssi值存入到RSSI中
                                    if (result.BSSID.equals(rssi.getAP1MAC())) {
                                        rssi.setAP1RSSI(result.level);
                                        tempbuffer.append(result.BSSID).append(":").append(result.level).append("DBm\n");
                                    }
                                    if (result.BSSID.equals(rssi.getAP2MAC())) {
                                        rssi.setAP2RSSI(result.level);
                                        tempbuffer.append(result.BSSID).append(":").append(result.level).append("DBm\n");
                                    }
                                    if (result.BSSID.equals(rssi.getAP3MAC())) {
                                        rssi.setAP3RSSI(result.level);
                                        tempbuffer.append(result.BSSID).append(":").append(result.level).append("DBm\n");
                                    }
                                }
                            }
                            new SendDateToServer(handler).getAsyn(rssi, 1);
                            tempbuffer.append("数据已成功发送");
                            tempbuffer.append("\n");

                            tempbuffer.append(buffer);
                            buffer = tempbuffer;
                            if (buffer.length() > 2048) buffer.delete(0, buffer.length());

                            handler.sendEmptyMessage(COMPLETED);
                            //尝试发送数据给服务器
                            try {
                                Thread.sleep(3000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        handler.sendEmptyMessage(END);
                    }
                }).start();
            }
        });


        //扫描
        scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> testlist = new ArrayList<>();

                List<ScanResult> results = scanWifiResult();
                for (ScanResult result : results) {
                    testlist.add(result.SSID + "@" + result.BSSID);
                }
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                intent.putExtra("wifidata", resource.dataForIntent(testlist));
                startActivityForResult(intent, 1);
            }
        });

        //定位
        location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.sendEmptyMessage(START);
                rssi.setNumber(114514);
                flag = true;
                wifiText.setText("定位开始");
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        for (int i2 = 0; i2 < 2; i2++) {
                            scanWifiResult();
                            try {
                                Thread.sleep(3000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        while (flag) {
                            //扫描列表，获取wifi列表
                            List<ScanResult> results = scanWifiResult();
                            //对扫描结果进行处理
                            if (results.isEmpty())
                                Log.d("scanResult", "扫描失败");
                            else {
                                Log.d("scanResult", "扫描成功");
                                for (ScanResult result : results) {
                                    //进行判断，将获取到的rssi值存入到RSSI中
                                    if (result.BSSID.equals(rssi.getAP1MAC())) {
                                        rssi.setAP1RSSI(result.level);
                                    }
                                    if (result.BSSID.equals(rssi.getAP2MAC())) {
                                        rssi.setAP2RSSI(result.level);
                                    }
                                    if (result.BSSID.equals(rssi.getAP3MAC())) {
                                        rssi.setAP3RSSI(result.level);
                                    }
                                }
                            }
                            //尝试发送数据给服务器
                            // new SendDateToServer(handler).SendDataToServer(rssi.getNumber().toString(), rssi.toString());
                            new SendDateToServer(handler).getAsyn(rssi, 2);
                            try {
                                Thread.sleep(3000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();


            }
        });

        stopLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wifiText.setText("定位结束");
                flag = false;
                handler.sendEmptyMessage(END);
            }
        });

    }
    @SuppressLint("SetTextI18n")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == Activity.RESULT_OK) {
                if (data != null) {
                    String[] s = resource.getData(data.getStringExtra("data_return"));
                    rssi = new RSSI(
                            s[0].substring(s[0].indexOf("@") + 1),
                            s[1].substring(s[1].indexOf("@") + 1),
                            s[2].substring(s[2].indexOf("@") + 1)
                    );
                    showSelectedWiFi.setText(s[0] + "\n" + s[1] + "\n" + s[2]);
                    gather.setEnabled(true);
                    location.setEnabled(true);
                }
            }

            if (resultCode == Activity.RESULT_CANCELED) {

            }
        }
    }

    //扫描WiFi
    public List<ScanResult> scanWifiResult() {
        //扫描列表，获取wifi列表
        wifiManager.startScan();
        List<ScanResult> results = wifiManager.getScanResults();
        return results;
    }

}
